#!/usr/bin/env python3
"""
S1手环数据解析Web应用
Flask后端API - 重构版本
使用蓝图模块化架构
"""

import os
import logging
from flask import Flask, jsonify
from flask_cors import CORS

from config import config
from api.data_parse import file_bp
from api.eda_analysis import eda_bp
from api.static_routes import static_bp
from api.health import health_bp
from api.ppg_analysis import ppg_bp

def create_app(config_name=None):
    """应用工厂函数"""
    if config_name is None:
        config_name = os.environ.get('FLASK_ENV', 'default')
    
    # 创建Flask应用
    app = Flask(__name__)
    
    # 加载配置
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    
    # 配置日志
    logging.basicConfig(
        level=getattr(logging, app.config['LOG_LEVEL']),
        format=app.config['LOG_FORMAT']
    )
    logger = logging.getLogger(__name__)
    
    # 启用CORS
    CORS(app)
    
    # 注册蓝图
    app.register_blueprint(static_bp)
    app.register_blueprint(health_bp, url_prefix='/api/health')
    app.register_blueprint(file_bp, url_prefix='/api/files')
    app.register_blueprint(eda_bp, url_prefix='/api/eda')
    app.register_blueprint(ppg_bp, url_prefix='/api/ppg')
    
    # 全局错误处理
    @app.errorhandler(404)
    def not_found(error):
        """404错误处理"""
        return jsonify({'error': '接口不存在'}), 404

    @app.errorhandler(500)
    def internal_error(error):
        """500错误处理"""
        return jsonify({'error': '服务器内部错误'}), 500
    
    logger.info("S1手环数据解析Web应用初始化完成")
    return app

# 创建应用实例
app = create_app()

if __name__ == '__main__':
    import logging
    logger = logging.getLogger(__name__)
    logger.info("启动S1手环数据解析Web应用...")
    
    # 获取环境变量配置
    debug_mode = os.environ.get('FLASK_DEBUG', '1') == '1'
    host = os.environ.get('FLASK_HOST', '0.0.0.0')
    port = int(os.environ.get('FLASK_PORT', '5000'))
    
    app.run(debug=debug_mode, host=host, port=port, use_reloader=debug_mode)